<template>
  <div class="case-documents">
    <!-- 顶部搜索栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="container mx-auto px-4 py-3">
        <div class="flex justify-between items-center mb-4">
          <h1 class="text-xl font-bold text-gray-800">案件文书</h1>
          <button @click="refreshDocuments" class="text-blue-600">
            <i class="fas fa-sync-alt"></i>
          </button>
        </div>
        
        <!-- 搜索和筛选 -->
        <div class="flex flex-col md:flex-row gap-4">
          <div class="flex-1">
            <div class="relative">
              <input 
                v-model="searchKeyword" 
                type="text" 
                placeholder="搜索文书名称..."
                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
              <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>
          </div>
          
          <select v-model="selectedCategory" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
            <option value="">所有类型</option>
            <option value="accident">事故材料</option>
            <option value="medical">医疗文档</option>
            <option value="insurance">保险文件</option>
            <option value="appraisal">鉴定报告</option>
            <option value="lawsuit">法律文书</option>
            <option value="other">其他文件</option>
          </select>
        </div>
      </div>
    </header>

    <!-- 文书列表 -->
    <div class="container mx-auto px-4 py-6">
      <!-- 统计信息 -->
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg p-4 shadow-sm text-center">
          <div class="text-2xl font-bold text-blue-600">{{ totalDocuments }}</div>
          <div class="text-sm text-gray-600">总文书数</div>
        </div>
        <div class="bg-white rounded-lg p-4 shadow-sm text-center">
          <div class="text-2xl font-bold text-green-600">{{ downloadableCount }}</div>
          <div class="text-sm text-gray-600">可下载</div>
        </div>
        <div class="bg-white rounded-lg p-4 shadow-sm text-center">
          <div class="text-2xl font-bold text-orange-600">{{ pendingCount }}</div>
          <div class="text-sm text-gray-600">待生成</div>
        </div>
        <div class="bg-white rounded-lg p-4 shadow-sm text-center">
          <div class="text-2xl font-bold text-purple-600">{{ recentCount }}</div>
          <div class="text-sm text-gray-600">最近更新</div>
        </div>
      </div>

      <!-- 文书分类标签 -->
      <div class="flex flex-wrap gap-2 mb-6">
        <button 
          v-for="category in categories" 
          :key="category.key"
          @click="selectedCategory = category.key"
          :class="[
            'px-4 py-2 rounded-full text-sm font-medium transition-colors',
            selectedCategory === category.key 
              ? 'bg-blue-600 text-white' 
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
          ]"
        >
          <i :class="category.icon" class="mr-1"></i>
          {{ category.name }}
          <span class="ml-1 text-xs">({{ category.count }})</span>
        </button>
      </div>

      <!-- 文书卡片列表 -->
      <div class="space-y-4">
        <div 
          v-for="document in filteredDocuments" 
          :key="document.id"
          class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow"
        >
          <div class="p-6">
            <div class="flex justify-between items-start mb-4">
              <div class="flex-1">
                <div class="flex items-center mb-2">
                  <div class="document-icon mr-3">
                    <i :class="getDocumentIcon(document.type)" class="text-2xl"></i>
                  </div>
                  <div>
                    <h3 class="text-lg font-semibold text-gray-800">{{ document.title }}</h3>
                    <p class="text-sm text-gray-600">{{ document.description }}</p>
                  </div>
                </div>
                
                <div class="flex items-center space-x-4 text-sm text-gray-500">
                  <span><i class="fas fa-calendar mr-1"></i>{{ formatDate(document.createdAt) }}</span>
                  <span><i class="fas fa-file-alt mr-1"></i>{{ document.fileSize }}</span>
                  <span><i class="fas fa-user mr-1"></i>{{ document.creator }}</span>
                </div>
              </div>
              
              <div class="flex items-center space-x-2">
                <span 
                  :class="getStatusClass(document.status)"
                  class="px-3 py-1 rounded-full text-xs font-medium"
                >
                  {{ getStatusText(document.status) }}
                </span>
              </div>
            </div>

            <!-- 文档操作 -->
            <div class="flex justify-between items-center pt-4 border-t border-gray-100">
              <div class="text-sm text-gray-600">
                <span v-if="document.lastDownload">
                  最后下载: {{ formatDate(document.lastDownload) }}
                </span>
                <span v-else>未下载</span>
              </div>
              
              <div class="flex space-x-2">
                <button 
                  v-if="document.status === 'ready'"
                  @click="showDocumentPreview(document)"
                  class="px-4 py-2 text-blue-600 border border-blue-600 rounded-lg hover:bg-blue-50 transition-colors"
                >
                  <i class="fas fa-eye mr-1"></i>预览
                </button>
                
                <button 
                  v-if="document.status === 'ready'"
                  @click="downloadDocument(document)"
                  class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  <i class="fas fa-download mr-1"></i>下载
                </button>
                
                <button 
                  v-if="document.status === 'pending'"
                  class="px-4 py-2 bg-gray-300 text-gray-500 rounded-lg cursor-not-allowed"
                  disabled
                >
                  <i class="fas fa-clock mr-1"></i>生成中
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredDocuments.length === 0" class="text-center py-12">
        <div class="text-gray-400 mb-4">
          <i class="fas fa-file-alt text-6xl"></i>
        </div>
        <h3 class="text-lg font-medium text-gray-600 mb-2">暂无文书</h3>
        <p class="text-gray-500">当前筛选条件下没有找到相关文书</p>
      </div>
    </div>

    <!-- 文档预览弹窗 -->
    <div v-if="showPreview" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
      <div class="bg-white rounded-lg max-w-4xl w-full max-h-screen overflow-hidden">
        <div class="flex justify-between items-center p-4 border-b">
          <h3 class="text-lg font-semibold">{{ previewDocument?.title }}</h3>
          <button @click="closePreview" class="text-gray-500 hover:text-gray-700">
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>
        <div class="p-4 overflow-y-auto" style="max-height: calc(100vh - 200px);">
          <!-- 这里可以集成PDF预览或其他文档预览组件 -->
          <div class="text-center py-8">
            <i class="fas fa-file-alt text-6xl text-gray-300 mb-4"></i>
            <p class="text-gray-600">文档预览功能</p>
            <p class="text-sm text-gray-500">{{ previewDocument?.title }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { caseApi } from '@/api/case'
import dayjs from 'dayjs'

export default {
  name: 'CaseDocuments',
  setup() {
    const documents = ref([])
    const searchKeyword = ref('')
    const selectedCategory = ref('')
    const showPreview = ref(false)
    const previewDocument = ref(null)
    
    // 交通事故文书分类
    const categories = ref([
      { key: '', name: '全部', icon: 'fas fa-list', count: 0 },
      { key: 'accident', name: '事故材料', icon: 'fas fa-car-crash', count: 0 },
      { key: 'medical', name: '医疗文档', icon: 'fas fa-hospital', count: 0 },
      { key: 'insurance', name: '保险文件', icon: 'fas fa-shield-alt', count: 0 },
      { key: 'appraisal', name: '鉴定报告', icon: 'fas fa-stethoscope', count: 0 },
      { key: 'lawsuit', name: '法律文书', icon: 'fas fa-gavel', count: 0 },
      { key: 'other', name: '其他文件', icon: 'fas fa-file', count: 0 }
    ])
    
    // 交通事故案件文档模拟数据
    const mockDocuments = [
      {
        id: 1,
        title: '道路交通事故认定书',
        description: '浦东交警大队出具的事故责任认定书（对方全责）',
        type: 'accident',
        status: 'ready',
        fileSize: '2.1MB',
        creator: '浦东交警大队',
        createdAt: '2024-01-25 10:00:00',
        lastDownload: '2024-02-01 14:20:00'
      },
      {
        id: 2,
        title: '事故现场照片集',
        description: '交通事故现场勘查照片，共15张高清图片',
        type: 'accident',
        status: 'ready',
        fileSize: '12.5MB',
        creator: '交警现场勘查',
        createdAt: '2024-01-15 15:30:00',
        lastDownload: '2024-01-30 09:15:00'
      },
      {
        id: 3,
        title: '入院记录',
        description: '上海第六人民医院急诊科入院记录',
        type: 'medical',
        status: 'ready',
        fileSize: '1.8MB',
        creator: '上海六院',
        createdAt: '2024-01-15 16:00:00',
        lastDownload: '2024-02-05 11:30:00'
      },
      {
        id: 4,
        title: 'CT检查报告',
        description: '颈椎、腰椎CT检查报告及影像资料',
        type: 'medical',
        status: 'ready',
        fileSize: '8.2MB',
        creator: '上海六院影像科',
        createdAt: '2024-01-16 09:15:00',
        lastDownload: '2024-02-03 14:20:00'
      },
      {
        id: 5,
        title: '手术记录',
        description: '腰椎内固定手术记录及麻醉记录',
        type: 'medical',
        status: 'ready',
        fileSize: '3.4MB',
        creator: '骨科主治医师',
        createdAt: '2024-01-16 14:30:00',
        lastDownload: '2024-02-08 10:45:00'
      },
      {
        id: 6,
        title: '出院小结',
        description: '住院治疗28天的出院小结及诊断证明',
        type: 'medical',
        status: 'ready',
        fileSize: '1.9MB',
        creator: '上海六院',
        createdAt: '2024-02-12 10:00:00',
        lastDownload: '2024-02-12 16:20:00'
      },
      {
        id: 7,
        title: '车辆定损报告',
        description: '受损车辆维修费用评估报告',
        type: 'insurance',
        status: 'ready',
        fileSize: '2.8MB',
        creator: '中国人保定损员',
        createdAt: '2024-02-01 14:00:00',
        lastDownload: '2024-02-05 09:30:00'
      },
      {
        id: 8,
        title: '保险理赔申请书',
        description: '向保险公司提交的理赔申请材料',
        type: 'insurance',
        status: 'ready',
        fileSize: '1.5MB',
        creator: '李卫民律师',
        createdAt: '2024-02-05 16:00:00',
        lastDownload: null
      },
      {
        id: 9,
        title: '司法鉴定委托书',
        description: '委托华东政法司法鉴定中心进行伤残鉴定',
        type: 'appraisal',
        status: 'ready',
        fileSize: '1.2MB',
        creator: '李卫民律师',
        createdAt: '2024-02-10 10:00:00',
        lastDownload: '2024-02-14 15:20:00'
      },
      {
        id: 10,
        title: '伤残等级鉴定报告',
        description: '九级伤残鉴定报告及三期鉴定意见书',
        type: 'appraisal',
        status: 'pending',
        fileSize: '待生成',
        creator: '华东政法司法鉴定中心',
        createdAt: '2024-02-16 09:00:00',
        lastDownload: null
      },
      {
        id: 11,
        title: '委托代理合同',
        description: '与律师事务所签署的委托代理合同',
        type: 'lawsuit',
        status: 'ready',
        fileSize: '1.6MB',
        creator: '李卫民律师',
        createdAt: '2024-01-30 09:00:00',
        lastDownload: '2024-01-30 10:30:00'
      },
      {
        id: 12,
        title: '赔偿计算清单',
        description: '详细的赔偿项目及金额计算明细',
        type: 'lawsuit',
        status: 'pending',
        fileSize: '待生成',
        creator: '李卫民律师',
        createdAt: '2024-02-18 14:00:00',
        lastDownload: null
      },
      {
        id: 13,
        title: '医疗费发票清单',
        description: '所有医疗费用发票及明细汇总',
        type: 'other',
        status: 'ready',
        fileSize: '4.2MB',
        creator: '财务整理',
        createdAt: '2024-02-14 16:00:00',
        lastDownload: '2024-02-15 11:20:00'
      }
    ]
    
    onMounted(() => {
      documents.value = mockDocuments
      updateCategoryCounts()
    })
    
    // 更新分类计数
    const updateCategoryCounts = () => {
      categories.value.forEach(category => {
        if (category.key === '') {
          category.count = documents.value.length
        } else {
          category.count = documents.value.filter(doc => doc.type === category.key).length
        }
      })
    }
    
    // 过滤后的文档
    const filteredDocuments = computed(() => {
      let filtered = documents.value
      
      if (searchKeyword.value) {
        filtered = filtered.filter(doc => 
          doc.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
          doc.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
      }
      
      if (selectedCategory.value) {
        filtered = filtered.filter(doc => doc.type === selectedCategory.value)
      }
      
      return filtered
    })
    
    // 统计信息
    const totalDocuments = computed(() => documents.value.length)
    const downloadableCount = computed(() => documents.value.filter(doc => doc.status === 'ready').length)
    const pendingCount = computed(() => documents.value.filter(doc => doc.status === 'pending').length)
    const recentCount = computed(() => {
      const threeDaysAgo = dayjs().subtract(3, 'day')
      return documents.value.filter(doc => dayjs(doc.createdAt).isAfter(threeDaysAgo)).length
    })
    
    // 获取交通事故文档图标
    const getDocumentIcon = (type) => {
      const iconMap = {
        accident: 'fas fa-car-crash text-red-500',
        medical: 'fas fa-hospital text-blue-500',
        insurance: 'fas fa-shield-alt text-green-500',
        appraisal: 'fas fa-stethoscope text-purple-500',
        lawsuit: 'fas fa-gavel text-orange-500',
        other: 'fas fa-file text-gray-500'
      }
      return iconMap[type] || iconMap.other
    }
    
    // 获取状态样式
    const getStatusClass = (status) => {
      const statusMap = {
        ready: 'bg-green-100 text-green-800',
        pending: 'bg-yellow-100 text-yellow-800',
        error: 'bg-red-100 text-red-800'
      }
      return statusMap[status] || statusMap.ready
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        ready: '可下载',
        pending: '生成中',
        error: '生成失败'
      }
      return statusMap[status] || '未知'
    }
    
    // 格式化日期
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }
    
    // 刷新文档
    const refreshDocuments = async () => {
      try {
        // 这里应该调用实际的API
        // const response = await caseApi.getCaseDocuments()
        // documents.value = response.data
        console.log('刷新文档列表')
      } catch (error) {
        console.error('刷新失败:', error)
      }
    }
    
    // 预览文档
    const showDocumentPreview = (document) => {
      previewDocument.value = document
      showPreview.value = true
    }
    
    // 关闭预览
    const closePreview = () => {
      showPreview.value = false
      previewDocument.value = null
    }
    
    // 下载文档
    const downloadDocument = async (document) => {
      try {
        // 这里应该调用实际的下载API
        console.log('下载文档:', document.title)
        
        // 更新最后下载时间
        document.lastDownload = dayjs().format('YYYY-MM-DD HH:mm:ss')
        
        // 模拟下载
        const link = document.createElement('a')
        link.href = '#' // 实际应该是文件URL
        link.download = document.title
        link.click()
      } catch (error) {
        console.error('下载失败:', error)
      }
    }
    
    return {
      documents,
      searchKeyword,
      selectedCategory,
      categories,
      filteredDocuments,
      totalDocuments,
      downloadableCount,
      pendingCount,
      recentCount,
      showPreview,
      previewDocument,
      getDocumentIcon,
      getStatusClass,
      getStatusText,
      formatDate,
      refreshDocuments,
      showDocumentPreview,
      closePreview,
      downloadDocument
    }
  }
}
</script>

<style scoped>
.case-documents {
  padding: 20px 0;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 20px;
}

.documents-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style> 